<template>
  <el-dialog v-model="dialogFormVisible" :title="title" @close="closeDialog">
    <el-form :model="addAppForm" ref="addAppRef" :rules="addApprules">
      <el-form-item label="上传签名" :label-width="formLabelWidth" prop="imgUrl">
        <img v-if="addAppForm.imgUrl" :src="addAppForm.imgUrl" class="name_img" ref="imageElement">
        <el-upload ref="uploadRef" class="upload-demo" :on-change="handleFileChangedata" :auto-upload="false"
          :show-file-list="false">
          <template #trigger>
            <el-button type="primary">{{ addAppForm.imgUrl ? '重新上传' : '上传图片' }}</el-button>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <!-- <el-button @click="cancel()">取消</el-button> -->
        <el-button type="primary" @click="dialogFormVisible = false">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref } from "vue";
import { httpService } from "@/utils/httpService";
import { ElMessage, ElForm } from "element-plus";

import { vxRule } from "@/utils/validator";

export default {
  name: "AddApp",
  components: { ElForm, ElMessage },
  mounted() {
    this.user = JSON.parse(sessionStorage.getItem('user'))
  },
  data() {
    return {
      dialogFormVisible: ref(false),
      formLabelWidth: "120px",
      title: "",
      id: "",
      personnelType: "",
      baseRoleList: [],
      user: {},
      addAppForm: {
        imgUrl: "",
      },
      // 校验规则
      addApprules: {
        imgUrl: vxRule(true, null, "blur"),
      },
    };
  },
  methods: {
    closeDialog() {
      this.clear();
    },
    cancel() {
      this.dialogFormVisible = false;
      this.clear();
    },
    clear() {
      this.dialogFormVisible = false;
      this.addAppForm.imgUrl = "";
      this.id = "";
    },
    handleFileChangedata(value) {
      const file = value.raw
      if (!file) return;
      this.setEsign(file)

      // this.resizeImage(file, 55, 40)

      // const reader = new FileReader();
      // reader.onload = (e) => {
      //   const img = new Image();
      //   img.onload = () => {
      //     let canvas = document.createElement('canvas');
      //     let ctx = canvas.getContext('2d');
      //     canvas.width = img.height;
      //     canvas.height = img.width;
      //     ctx.fillStyle = '#FFFFFF';
      //     ctx.fillRect(0, 0, canvas.width, canvas.height);
      //     if (img.height > img.width) {
      //       // canvas.width = img.height;
      //       // canvas.height = img.width;
      //       ctx.rotate(-Math.PI / 2); // 逆时针旋转90度
      //       ctx.drawImage(img, (-img.height / 12) * 9, 0);

      //       canvas.toBlob((blob) => {
      //         const rotatedFile = new File([blob], file.name, { type: file.type });
      //         console.log(123123, rotatedFile);
      //         this.handel(rotatedFile)
      //         this.changeFileHandle(rotatedFile)

      //         // this.setEsign(file)
      //       }, file.type);
      //     } else {

      //       this.changeFileHandle(file)
      //       // this.setEsign(file)
      //     }

      //   };

      //   // 将读取到的文件内容设置为图片源
      //   img.src = e.target.result;
      // };

      // // // 读取文件内容
      // reader.readAsDataURL(file);
    },

    handel(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const img = new Image();
        // 将读取到的文件内容设置为图片源
        img.src = e.target.result;
      };
      reader.readAsDataURL(file);
    },

    changeFileHandle(value) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const img = new Image();
        const timeData = new Date().getTime();

        img.src = e.target.result;
        img.onload = () => {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          canvas.width = 55;
          canvas.height = 35;
          ctx.fillStyle = '#FFFFFF';
          ctx.fillRect(0, 0, canvas.width, canvas.height);
          const maxWidth = 55; // 设置最大宽度
          const maxHeight = 35; // 设置最大高度
          let width = img.width;
          let height = img.height;
          if (width > height) {
            if (width > maxWidth) {
              height *= maxWidth / width;
              width = maxWidth;
            }
          } else {
            if (height > maxHeight) {
              width *= maxHeight / height;
              height = maxHeight;
            }
          }
          // canvas.width = width;
          // canvas.height = height;
          ctx.drawImage(img, 0, 0, width, height);
          canvas.toBlob((blob) => {
            const fileimg = new File([blob], `${timeData}${this.user.teacherNumber}.png`, { type: 'image/jpeg' })
            console.log(22222, fileimg);
            this.setEsign(fileimg)
            // this.addAppForm.imgUrl = img.src
          }, 'image/jpeg', 2); // 0.8 是压缩质量，可根据需要调整
        };

      };
      reader.readAsDataURL(value);
    },



    getEsign() {
      console.log(123, this.id == this.user.id);
      if (this.id == this.user.id) {
        httpService("/javaApi/baseTeacher/getEsign", {}, "get").then(
          (data) => {
            if (data.object) {
              this.addAppForm.imgUrl = "https://wx.zhengzhong.cn" + data.object
              // this.addAppForm.imgUrl = "http://192.168.9.20" + data.object
            } else {
              this.addAppForm.imgUrl = ""
            }

          }
        );
      } else {
        httpService("/javaApi/baseTeacher/getOtherEsign", { 'id': this.id }, "get").then(
          (data) => {
            console.log(data);
            if (data.object) {
              this.addAppForm.imgUrl = "https://wx.zhengzhong.cn" + data.object
              // this.addAppForm.imgUrl = "http://192.168.9.20" + data.object
            } else {
              this.addAppForm.imgUrl = ""
            }

          }
        );
      }
    },
    setEsign(imgFile) {
      // console.log(456,this.id == this.user.id);
      if (this.id == this.user.id) {
        let params = new FormData()
        params.append("file", imgFile)
        httpService("/javaApi/baseTeacher/setEsign", params, "post").then(
          (data) => {
            if (data.object) {
              this.addAppForm.imgUrl = "https://wx.zhengzhong.cn" + data.object
            } else {
              this.addAppForm.imgUrl = ""
            }
          }
        );
      } else {
        console.log(this.id);
        let params = new FormData()
        params.append("file", imgFile)
        params.append("id", this.id)
        httpService("/javaApi/baseTeacher/setEsign", params, "post").then(
          (data) => {
            if (data.object) {
              this.addAppForm.imgUrl = "https://wx.zhengzhong.cn" + data.object
            } else {
              this.addAppForm.imgUrl = ""
            }
          }
        );

      }

    },
    save() {

    },
  },
};
</script>
<style>
.el-my-select {
  display: inline-block;
  position: relative;
  line-height: 32px;
  width: 100%;
}

.el-dialog__header {
  padding: var(--el-dialog-padding-primary);
  padding-bottom: 10px;
  border-bottom: 1px solid #dedede;
  margin-right: 0;
}

.name_img {
  /* width: 100px; */
  margin-right: 20px;
}
</style>